<script lang="ts" setup>
import dayjs from 'dayjs';
import { Page, useVbenModal } from '@vben/common-ui';
import { ref } from 'vue';
import { Button, Card, message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { getFamilyApi, saveHeightWeightApi} from '#/api';
import { $t } from '#/locales';

import type { SelectProps } from 'ant-design-vue';
// import { preferences } from '@vben/preferences';

const nameOptions = ref<SelectProps['options']>([]);
async function fetchData() {
  try {
    const result = await getFamilyApi();
    const newOptions = result.map(item => ({
      label: item.name,
      value: item.name,
    }));
    if (nameOptions.value.length === 0) {
      nameOptions.value = newOptions;
    } else {
      // 合并newOptions和nameOptions的选项，并去重
      const mergedOptions = [...newOptions, ...nameOptions.value].reduce((acc, option) => {
        if (!acc.find(item => item.value === option.value)) {
          acc.push(option);
        }
        return acc;
      }, []);
      nameOptions.value = mergedOptions;
    }
    // console.log(nameOptions.value);
  } catch (error) {
    // 处理错误
    console.error(error);
  }
}

const [BaseForm] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showCollapseButton: false,
  collapsed: false,
  collapsedRows: 5,
  actionWrapperClass: 'text-center',
  commonConfig: {
    // 在label后显示一个冒号
    colon: true,
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: onSubmit,

  // 垂直布局，label和input在不同行，值为vertical
  // 水平布局，label和input在同一行
  layout: 'horizontal',
  schema: [
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Select',
      // 对应组件的参数
      componentProps: {
        allowClear: true,
        filterOption: true,
        placeholder: '请选择',
        showSearch: true,
        options: nameOptions,
        onDropdownVisibleChange: (visible: boolean) => {
          if (visible) {
            fetchData();
          }
        },
      },
      // 字段名
      fieldName: 'name',
      // 界面显示的label
      label: '姓名',
      rules: 'required',
    },

    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入身高',
      },
      fieldName: 'height',
      label: '身高',
      rules: 'required',
      suffix: () => 'cm',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入体重',
      },
      fieldName: 'weight',
      label: '体重',
      rules: 'required',
      suffix: () => 'kg',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入尺码',
      },
      fieldName: 'clothingSize',
      label: '衣服尺码',
      rules: 'required',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入尺码',
      },
      fieldName: 'shoeSize',
      label: '鞋子尺码',
      rules: 'required',
    },
    {
      component: 'DatePicker',
      fieldName: 'datePicker',
      componentProps: {
        showTime: true,
      },
      defaultValue: dayjs(),
      label: '日期',
      rules: 'selectRequired',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '自动生成',
        disabled: true,
      },
      dependencies: {
        trigger(values, form) {
          // 根据身高体重计算BMI
          const height = values.height
          const weight = values.weight
          if (height && weight) {
            const bmi = weight / (height / 100) ** 2
            form.setFieldValue('BMI', bmi.toFixed(2));
          }
        },
        // 只有指定的字段改变时，才会触发
        triggerFields: ['weight', 'height'],
      },
      fieldName: 'BMI',
      label: 'BMI',
    },
    {
      component: 'Segmented',
      componentProps: {
        options: ['偏瘦', '正常', '偏重', '肥胖'],
        disabled: true,
      },
      dependencies: {
        trigger(values, form) {
          const yourbmi = values.BMI;
          if (yourbmi) {
            let status = '正常';
            if (yourbmi < 18.5) {
              status = '偏瘦';
            } else if (yourbmi >= 24) {
              status = '偏重';
            } else if (yourbmi >= 28) {
              status = '肥胖';
            }
            form.setFieldValue('BMIStatus', status);
          }
        },
        triggerFields: ['BMI'],
      },
      fieldName: 'BMIStatus',
      label: 'BMI 状态',
      defaultValue: '正常',
    },
  ],
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-2',
});
function onSubmit(values: Record<string, any>) {
  // 格式化时间，避免时间格式不一致导致的问题
  values.datePicker = dayjs(values.datePicker).format('YYYY-MM-DD HH:mm:ss');
  // 如果当前语言是中文
  // if (preferences.app.locale === 'zh-CN') {
  //   values.datePicker = dayjs(values.datePicker).format('YYYY-MM-DD HH:mm:ss');
  //   message.info(values.datePicker);
  // }
  saveHeightWeightApi(JSON.stringify(values)).then(() => {
    message.success('保存成功');
  });
}

const [addForm, addFormAPI] = useVbenForm({
  wrapperClass: 'grid-cols-10', // 24栅格,
  commonConfig: {
    formItemClass: 'col-span-10',
    labelWidth: 50,
    // 在label后显示一个冒号
    colon: true,
  },
  handleSubmit: addFormSubmit,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入姓名',
      },
      fieldName: 'newName',
      label: '姓名',
      rules: 'required',
    },
  ],
  showDefaultActions: false,
});

function addFormSubmit(values: Record<string, any>) {
  const newOption = {
    label: values.newName,
    value: values.newName
  };
  // 检查是否已经存在相同的选项
  if (nameOptions.value.some(option => option.value === newOption.value)) {
    message.error('该选项已存在');
    addFormAPI.setFieldValue('newName', '');
    return;
  } else {
    nameOptions.value.push(newOption);
    modalApi.close();
    message.success('添加成功');
  };
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    await addFormAPI.validateAndSubmitForm();
    // modalApi.close();
  },
  title: '新增成员',
});

// 定义添加选项的函数
function addOption() {
  modalApi.open();
}

</script>

<template>
  <Page
    content-class="flex flex-col gap-4"
    description="身高体重管理"
    :title="$t('apps.heightWeight.title')"
  >
    <template #description>
      <div class="text-muted-foreground">
        <p>
          用于记录身高体重及衣服、鞋子尺码等信息。
        </p>
      </div>
    </template>
    <Card  title="信息录入">
      <template #extra>
        <Button type="primary" @click="addOption">新增成员</Button>
      </template>
      <BaseForm />
    </Card>
    <Modal class="w-[30%]">
      <div class="mx-auto max-w-lg p-12">
        <addForm />
      </div>
    </Modal>
  </Page>
</template>
